package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"math"
	"xialou_platform/app/requestx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/api/internal/cst"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentBindCountLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}
type baseResp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}
type usersInviteCardResp struct {
	Id                 string `json:"id"`
	Status             bool   `json:"status"`     // 状态   false 未使用 true已使用
	CardCode           string `json:"cardCode"`   // 卡号
	ParentUid          string `json:"parentUid"`  // 卡片绑定人员
	CreateTime         string `json:"createTime"` // 创建时间
	UpdateTime         string `json:"updateTime"`
	Year               int64  `json:"year"`
	Paid               bool   `json:"paid"`                 // 是否付费卡
	ExpireTime         string `json:"expireTime,omitempty"` // 过期时间
	UsageCount         int32  `json:"usageCount"`           // 使用次数
	SpcialUsageCount   int32  `json:"spcialUsageCount"`     // 专属使用次数
	Enable             bool   `json:"enable"`               // 是否有效卡
	ActivationDeadline string `json:"activationDeadline"`   // 激活截止时间
	Expired            bool   `json:"expired,omitempty"`    // 是否过期
	Available          bool   `json:"available"`
}
type userCardListResp struct {
	baseResp
	Data struct {
		baseResp
		CardList []usersInviteCardResp `json:"cardList"`
		Total    int64                 `json:"total"` // 总共卡片数量
	}
}

func NewAgentBindCountLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentBindCountLogic {
	return AgentBindCountLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentBindCountLogic) AgentBindCount() (resp *types.AgentBindCountResp, err error) {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		l.Error("获取用户id失败", err)
		return nil, err
	}
	// 获取绑定用户数量
	countResp, err := l.svcCtx.AgentRpc.AgentUserCount(l.ctx, &agentClient.AgentUserCountReq{
		AgentId: uid,
	})
	if err != nil {
		l.Error("rpc调用失败", err)
		resp = &types.AgentBindCountResp{
			BaseResp: types.BaseResp{
				Code: cst.ErrSystemError,
				Msg:  "System Error: agent rpc call failed",
			},
		}
		return
	}
	if countResp == nil {
		l.Error("rpc调用失败, countResp nil")
		resp = &types.AgentBindCountResp{
			BaseResp: types.BaseResp{
				Code: cst.ErrResponseNil,
				Msg:  "System Error: Response is nil And Error is nil",
			},
		}
		return
	}
	if countResp.Base.Code != agentClient.RespCode_OK {
		l.Error("rpc调用失败", err)
		return &types.AgentBindCountResp{
			BaseResp: types.BaseResp{
				Code: int64(countResp.Base.Code),
				Msg:  countResp.Base.Msg,
			},
		}, nil
	}

	// 获取绑定卡片数量 调用休闲吧Api
	cardResp, err := tools.RequestOtherPlatform(
		fmt.Sprintf("%s/%d?page=%d&pageSize=%d", l.svcCtx.Config.XiuXianApi.CardList, uid, 1, math.MaxInt64),
		"GET",
		l.svcCtx.Config.Auth.AccessSecret,
		"",
		l.svcCtx.Config.Auth.AccessExpire,
		10000, // admin_users表 下楼系统账户的ID
	)
	if err != nil {
		l.Error("获取绑定卡片数量失败", err)
		resp = &types.AgentBindCountResp{
			BaseResp: types.BaseResp{
				Code: cst.ErrSystemError,
				Msg:  "System Error: get card list failed",
			},
		}
		return
	}
	l.Info("获取绑定卡片数量成功", string(cardResp))
	var cardRespModel userCardListResp
	if err = json.Unmarshal(cardResp, &cardRespModel); err != nil {
		l.Error("解析绑定卡片数量失败", err)
		resp = &types.AgentBindCountResp{
			BaseResp: types.BaseResp{
				Code: cst.ErrSystemError,
				Msg:  "System Error: parse card list failed",
			},
		}
		return
	}

	return &types.AgentBindCountResp{
		BaseResp: types.BaseResp{
			Code: cst.OK,
			Msg:  "success",
		},
		Data: struct {
			CardTotal int64 `json:"cardTotal"`
			UserTotal int64 `json:"userTotal"`
		}{CardTotal: cardRespModel.Data.Total, UserTotal: countResp.Data.BindUserTotal},
	}, nil
}
